package com.brainwave.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.brainwave.R;

import java.util.List;

/**
 * 权限管理工具类
 * 处理应用权限的请求、检查和管理
 */
public class PermissionManager {
    
    private static final String TAG = "PermissionManager";
    
    private final Activity activity;
    private final Context context;
    
    public PermissionManager(Activity activity) {
        this.activity = activity;
        this.context = activity.getApplicationContext();
    }
    
    /**
     * 检查单个权限是否已授予
     */
    public boolean isPermissionGranted(String permission) {
        return ContextCompat.checkSelfPermission(context, permission) 
                == PackageManager.PERMISSION_GRANTED;
    }
    
    /**
     * 检查多个权限是否都已授予
     */
    public boolean arePermissionsGranted(String[] permissions) {
        for (String permission : permissions) {
            if (!isPermissionGranted(permission)) {
                return false;
            }
        }
        return true;
    }
    
    /**
     * 检查是否应该显示权限说明
     */
    public boolean shouldShowRequestPermissionRationale(String permission) {
        return ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
    }
    
    /**
     * 请求单个权限
     */
    public void requestPermission(String permission, int requestCode) {
        ActivityCompat.requestPermissions(activity, new String[]{permission}, requestCode);
    }
    
    /**
     * 请求多个权限
     */
    public void requestPermissions(String[] permissions, int requestCode) {
        ActivityCompat.requestPermissions(activity, permissions, requestCode);
    }
    
    /**
     * 显示权限说明对话框
     */
    public void showPermissionRationaleDialog(List<String> deniedPermissions) {
        StringBuilder message = new StringBuilder();
        message.append(context.getString(R.string.permission_rationale_message));
        message.append("\n\n");
        
        for (String permission : deniedPermissions) {
            message.append("• ").append(getPermissionDescription(permission)).append("\n");
        }
        
        new AlertDialog.Builder(activity)
                .setTitle(R.string.permission_rationale_title)
                .setMessage(message.toString())
                .setPositiveButton(R.string.permission_settings, (dialog, which) -> {
                    openAppSettings();
                })
                .setNegativeButton(R.string.permission_cancel, (dialog, which) -> {
                    dialog.dismiss();
                    handlePermissionDenied();
                })
                .setCancelable(false)
                .show();
    }
    
    /**
     * 获取权限的描述信息
     */
    private String getPermissionDescription(String permission) {
        switch (permission) {
            case android.Manifest.permission.BLUETOOTH:
            case android.Manifest.permission.BLUETOOTH_ADMIN:
            case android.Manifest.permission.BLUETOOTH_CONNECT:
            case android.Manifest.permission.BLUETOOTH_SCAN:
                return context.getString(R.string.permission_bluetooth_description);
                
            case android.Manifest.permission.ACCESS_COARSE_LOCATION:
            case android.Manifest.permission.ACCESS_FINE_LOCATION:
                return context.getString(R.string.permission_location_description);
                
            case android.Manifest.permission.INTERNET:
            case android.Manifest.permission.ACCESS_NETWORK_STATE:
                return context.getString(R.string.permission_network_description);
                
            case android.Manifest.permission.READ_EXTERNAL_STORAGE:
            case android.Manifest.permission.WRITE_EXTERNAL_STORAGE:
                return context.getString(R.string.permission_storage_description);
                
            default:
                return permission;
        }
    }
    
    /**
     * 打开应用设置页面
     */
    public void openAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", context.getPackageName(), null);
        intent.setData(uri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        
        try {
            activity.startActivity(intent);
        } catch (Exception e) {
            Logger.e(TAG, "Failed to open app settings", e);
            
            // 备用方案：打开应用管理页面
            try {
                Intent fallbackIntent = new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
                fallbackIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                activity.startActivity(fallbackIntent);
            } catch (Exception ex) {
                Logger.e(TAG, "Failed to open applications settings", ex);
            }
        }
    }
    
    /**
     * 处理权限被拒绝的情况
     */
    private void handlePermissionDenied() {
        Logger.w(TAG, "User denied permissions");
        
        // 显示功能受限提示
        new AlertDialog.Builder(activity)
                .setTitle(R.string.permission_denied_title)
                .setMessage(R.string.permission_denied_message)
                .setPositiveButton(R.string.permission_understood, (dialog, which) -> {
                    dialog.dismiss();
                })
                .show();
    }
    
    /**
     * 检查蓝牙权限
     */
    public boolean checkBluetoothPermissions() {
        String[] bluetoothPermissions = {
                android.Manifest.permission.BLUETOOTH,
                android.Manifest.permission.BLUETOOTH_ADMIN,
                android.Manifest.permission.ACCESS_COARSE_LOCATION,
                android.Manifest.permission.ACCESS_FINE_LOCATION
        };
        
        // Android 12+ 需要额外的蓝牙权限
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            String[] newBluetoothPermissions = {
                    android.Manifest.permission.BLUETOOTH_CONNECT,
                    android.Manifest.permission.BLUETOOTH_SCAN
            };
            
            // 合并权限数组
            String[] allPermissions = new String[bluetoothPermissions.length + newBluetoothPermissions.length];
            System.arraycopy(bluetoothPermissions, 0, allPermissions, 0, bluetoothPermissions.length);
            System.arraycopy(newBluetoothPermissions, 0, allPermissions, bluetoothPermissions.length, newBluetoothPermissions.length);
            
            return arePermissionsGranted(allPermissions);
        }
        
        return arePermissionsGranted(bluetoothPermissions);
    }
    
    /**
     * 检查网络权限
     */
    public boolean checkNetworkPermissions() {
        String[] networkPermissions = {
                android.Manifest.permission.INTERNET,
                android.Manifest.permission.ACCESS_NETWORK_STATE
        };
        
        return arePermissionsGranted(networkPermissions);
    }
    
    /**
     * 检查存储权限
     */
    public boolean checkStoragePermissions() {
        String[] storagePermissions = {
                android.Manifest.permission.READ_EXTERNAL_STORAGE,
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
        
        return arePermissionsGranted(storagePermissions);
    }
    
    /**
     * 显示蓝牙权限说明
     */
    public void showBluetoothPermissionRationale() {
        new AlertDialog.Builder(activity)
                .setTitle(R.string.bluetooth_permission_title)
                .setMessage(R.string.bluetooth_permission_rationale)
                .setPositiveButton(R.string.permission_grant, (dialog, which) -> {
                    // 重新请求蓝牙权限
                    requestBluetoothPermissions();
                })
                .setNegativeButton(R.string.permission_cancel, (dialog, which) -> {
                    dialog.dismiss();
                })
                .show();
    }
    
    /**
     * 请求蓝牙权限
     */
    private void requestBluetoothPermissions() {
        String[] bluetoothPermissions = {
                android.Manifest.permission.BLUETOOTH,
                android.Manifest.permission.BLUETOOTH_ADMIN,
                android.Manifest.permission.ACCESS_COARSE_LOCATION,
                android.Manifest.permission.ACCESS_FINE_LOCATION
        };
        
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            String[] newBluetoothPermissions = {
                    android.Manifest.permission.BLUETOOTH_CONNECT,
                    android.Manifest.permission.BLUETOOTH_SCAN
            };
            
            String[] allPermissions = new String[bluetoothPermissions.length + newBluetoothPermissions.length];
            System.arraycopy(bluetoothPermissions, 0, allPermissions, 0, bluetoothPermissions.length);
            System.arraycopy(newBluetoothPermissions, 0, allPermissions, bluetoothPermissions.length, newBluetoothPermissions.length);
            
            requestPermissions(allPermissions, Constants.PERMISSION_REQUEST_CODE);
        } else {
            requestPermissions(bluetoothPermissions, Constants.PERMISSION_REQUEST_CODE);
        }
    }
    
    /**
     * 显示位置权限说明（蓝牙扫描需要）
     */
    public void showLocationPermissionRationale() {
        new AlertDialog.Builder(activity)
                .setTitle(R.string.location_permission_title)
                .setMessage(R.string.location_permission_rationale)
                .setPositiveButton(R.string.permission_grant, (dialog, which) -> {
                    String[] locationPermissions = {
                            android.Manifest.permission.ACCESS_COARSE_LOCATION,
                            android.Manifest.permission.ACCESS_FINE_LOCATION
                    };
                    requestPermissions(locationPermissions, Constants.PERMISSION_REQUEST_CODE);
                })
                .setNegativeButton(R.string.permission_cancel, (dialog, which) -> {
                    dialog.dismiss();
                })
                .show();
    }
}